<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2017/1/19
 * Time: 下午8:21
 */
namespace app\admin\controller;

use think\Exception;
use think\Db;

class Region extends Common
{
    public function index()
    {   header("Content-type:text/html;charset=utf-8");
        //设置标题
        $this->templateTitle("地区列表");

        //获取所有的省
        $categoryList1 = Db::name("region")
            ->where("parent_id", 1)
			->where("level", 1)
            ->order("order_num DESC")
            ->select();
//        //获取所有市
        foreach ($categoryList1 as &$category1)
        {
            $categoryList2 = Db::name("region")
                ->where("level", 2)
                ->where("parent_id", $category1["id"])
                ->select();
            $category1["children"] = $categoryList2;
        }

        $this->assign("list1", $categoryList1);
		
        return $this->fetch();
    }

   

    //更改分类的可见性
    public function visible()
    {
        if (request()->isAjax())
        {
            //分类ID
            $categoryId = request()->param("cid");
            //获取可见性状态
            $status = request()->param("status");

            try
            {
                //修改分类及其子类的可见性
                Db::name("region")
                    ->where("id", $categoryId)
                    ->setField("is_visible", $status);

                return $this->ajaxSuccess("修改地区可见性成功！");
            }
            catch (Exception $exception)
            {
                return $this->ajaxError("修改地区可见性失败！");
            }
        }
    }

    public function edit()
    {   $cid = request()->param("cid");

        if(request()->isGet()){
            $this->layoutModal();
            $info = Db::name('region')->where('id',$cid)->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
        if (request()->isAjax())
        {
            $data['order_num'] = intval(input('order'));
            $data['is_visible'] = intval(input('visible'));

            try
            {
                //修改分类及其子类的可见性
                Db::name("region")
                    ->where("id", $cid)
                    ->update($data);

                return $this->ajaxSuccess("地区编辑成功！");
            }
            catch (Exception $exception)
            {
                return $this->ajaxError("地区编辑失败！");
            }
        }
    }
}